//
//  AppDelegate.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/25.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "AppDelegate.h"
#import "DALoginViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "JPUSHService.h"
#import "DAHomePageViewController.h"
#import "DAMessageDetailViewController.h"
#import "DATabBarViewController.h"
#import "DAMessageViewController.h"
#import "DALocalMessageSingletonModel.h"
#import "DAHomePageViewController.h"

@interface AppDelegate ()
@property (nonatomic, strong) NSDictionary *dic;

@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override
   // point for customization after application launch.
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
 
    /** 判断是否是第一次登录 */
     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
     BOOL isLogin = [userDefaults boolForKey:@"isLogin"];
    if (isLogin) {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        self.window.rootViewController = story.instantiateInitialViewController;
    } else{
        UIStoryboard *login = [UIStoryboard storyboardWithName:@"DALogin" bundle:nil];
        self.window.rootViewController = login.instantiateInitialViewController;
    }
    // 启动音效
//    NSURL *url = [[NSBundle mainBundle] URLForResource:@"7008.mp3" withExtension:nil];
//    SystemSoundID soundID = 0;
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
//    AudioServicesPlaySystemSound(soundID);
    
//    // 极光推送
    [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
   
//    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    NSString *appkey = @"0c7a3d8a2c8e2906a2f9a473";
    [JPUSHService setupWithOption:launchOptions appKey:appkey
                          channel:@"Publish channel"
                 apsForProduction:false
            advertisingIdentifier:nil];
    
//    
//    if (launchOptions) {
//        NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
//        
//        if (remoteNotification) {
//            NSLog(@"推送消息 === %@", remoteNotification);
//            
//        }
//    }
    // 获取自定义消息
//    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
   // NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
  //  NSLog(@"111111111%@", remoteNotification);
    
    NSLog(@"did  finish");
    
    // 创建记录角标的
    
    
    return YES;
}


//#pragma mark - 获取自定义消息
//- (void)networkDidReceiveMessage:(NSNotification *)notfication{
// 
//    NSDictionary *userInfo = [notfication userInfo];
//    NSLog(@"自定义消息:%@", userInfo);
////    NSString *content = [userInfo valueForKey:@"content"];
////    NSDictionary *extras = [userInfo valueForKey:@"extras"];
////    NSString *customizeField1 = [extras valueForKey:@"custimizeField1"];
//    
//}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    
//    // Required,For systems with less than or equal to iOS6
//    [JPUSHService handleRemoteNotification:userInfo];
//    
//    // 获取APNS 标准信息内容
//    NSDictionary *aps = [userInfo valueForKey:@"aps"];
//    
//    NSLog(@"6:%@", aps);
//   // NSString *content = [aps valueForKey:@"alert"];
//    
//    [application setApplicationIconBadgeNumber:0];
//}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

// 接收信息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    NSLog(@"收到的消息%@", userInfo);
    // 取出badge
    NSString *badge = userInfo[@"aps"][@"badge"];
    // 来通知之后 刷新单列的数据
  //  if ([userInfo[@"target"] isEqualToString:@"Message"]) {
//        DALocalMessageSingletonModel *model = [DALocalMessageSingletonModel sharedDALocalMessageSingletonModel];
//        NSUserDefaults *useDefaults = [NSUserDefaults standardUserDefaults];
//        NSString *lastReplyID = [useDefaults objectForKey:@"lastReplyID"];
       // [model prepareDataWithUserID:userInfo[@"replyUserID"] lastReplyID:lastReplyID];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedMessageForRefreshBadge" object:badge];
  //  }
    // 页面跳转
    if (application.applicationState == UIApplicationStateActive) {
        NSLog(@"111");
        
    } else if (application.applicationState == UIApplicationStateInactive){
        NSLog(@"22");
        if ([userInfo[@"target"] isEqualToString:@"Message"]) {
            [self receivedMessage:userInfo];
            
        }
        if ([userInfo[@"target"] isEqualToString:@"HomePage"]) {
            [self goToHomePage:userInfo];
        }
        
    }
}
#pragma mark - 收到Message的消息时
- (void)receivedMessage:(NSDictionary *)dic{
    DALocalMessageSingletonModel *model = [DALocalMessageSingletonModel sharedDALocalMessageSingletonModel];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *lastID = [userDefaults objectForKey:@"lastReplyID"];
   [model prepareDataWithUserID:dic[@"replyUserID"] lastReplyID:lastID pageNumber:@"0"  block:^(BOOL isSuccessful) {
       if (isSuccessful) {
           NSLog(@"数据更新了");
           // 通知页面更新数据
           [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationUpData" object:nil];
       }else{
           NSLog(@"数据更新失败");
       }
   }];
    // 页面跳转
    DAMessageDetailViewController *messageDetail = [[DAMessageDetailViewController alloc]init];
    messageDetail.timelineID = dic[@"timelineId"];
    messageDetail.hidesBottomBarWhenPushed = YES;
    messageDetail.isShowNowMessage = YES;
    UIViewController *viewController = [AppDelegate topViewController];
    [viewController.navigationController pushViewController:messageDetail animated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CleanMessageBadge" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TURNMESSAGEDETAIL" object:nil];
}
#pragma mark - 跳转首页
- (void)goToHomePage:(NSDictionary *)dic{
    DALocalMessageSingletonModel *model = [DALocalMessageSingletonModel sharedDALocalMessageSingletonModel];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *lastID = [userDefaults objectForKey:@"lastReplyID"];
    [model prepareDataWithUserID:dic[@"userID"] lastReplyID:lastID pageNumber:@"0" block:^(BOOL isSuccessful) {
        if (isSuccessful) {
            NSLog(@"消息页面数据更新");
            // 通知页面更新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationUpData" object:nil];
        }else{
            NSLog(@"数据更新失败");
        }
    }];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectIndex" object:[NSString stringWithFormat:@"%d", 0]];

}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}
#pragma mark - 跟消息页面点击 进入指定页面
//- (void)goToMessageViewControllerWith:(NSDictionary *)msgDic{
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    [userDefaults setObject:@"push" forKey:@"push"];
//    [userDefaults synchronize];
//    NSString *targetStr = [msgDic objectForKey:@"target"];
//    if ([targetStr isEqualToString:@"Homepage"]) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"MessageToController" object:[NSString stringWithFormat:@"%d", 0]];
//    }
//    if ([targetStr isEqualToString:@"Message"]) {
//        DAMessageDetailViewController *MessageDetail = [[DAMessageDetailViewController alloc]init];
//        MessageDetail.timelineID = msgDic[@"timelineId"];
//        MessageDetail.hidesBottomBarWhenPushed = YES;
//        UIViewController *viewController = [AppDelegate topViewController];
//        [viewController.navigationController pushViewController:MessageDetail animated:YES];
//        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        [userDefaults setBool:NO forKey:@"isPostMessage"];
//        
//    }
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    // 清除角标
//    [application setApplicationIconBadgeNumber:0];
//    if (!(application.applicationState == UIApplicationStateActive)) {
//        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        BOOL isSuccess = [userDefaults objectForKey:@"isPostMessage"];
//        if (isSuccess) {
//           // [self goToMessageViewControllerWith:self.dic];
//        }
//    }
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    [JPUSHService resetBadge];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//顶层的viewCotroller
+ (UIViewController*)topViewController{
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
+ (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}



@end
